from ats.db import dao
from ats.re import relib

# -----------------------------------------------------------------------------
# URL functions
# -----------------------------------------------------------------------------
def get_handle(uri):
	""" This function will return the "handle" section of the uri
			this is the part of the uri that dispatcher.py uses to determine
			what the resource is... 
			e.g.: 
				> get_handle("/cool/page/here?name=val")
				> "cool"

			Note: "handle section" is just an ats thing that allows for simple 
				url to resource mapping without regexes.  It is not quite a flexible
				as using regexes but much easier on the eyes when you have to edit
				urlmap.conf
	"""
	if not uri:
		return ""
	m = relib.URL_HANDLE.search(uri)
	if m:
		g = m.groups()
		if g and len(g)>0:
			return g[0]
	return ""

# -----------------------------------------------------------------------------
def unpack(uri, keys, keep_blank_values=0):
	""" This function will take a req.uri and a list and return a dict
			of key->val pairs where the keys are taken from the key list argument
			and values are taken from the req.uri.split('/')

			It is meant to be used w/ REST style uri's only
	"""
	d = {}
	if keep_blank_values:
		for key in keys:
			d[key] = None
	if not uri or not keys:
		return d
	try:
		num_keys = len(keys)	
		tokens = uri.split('/')[2:]
		for i in xrange(len(tokens)):
			if i < num_keys and tokens[i]:
				d[keys[i]] = tokens[i]
		return d
	except: 
		return d

# -----------------------------------------------------------------------------
# units
# -----------------------------------------------------------------------------
if __name__ == "__main__":
	print "keep_blank_values=0"
	print """/cool/666/42 - ['evilid', 'goodid']"""
	d = unpack("/cool/666/42", ['evilid', 'goodid'])
	for k,v in d.items(): print k, v
	
	print """/cool/666/42 - ['evilid']"""
	d = unpack("/cool/666/42", ['evilid'])
	for k,v in d.items(): print k, v
 
	print """/cool/666 - ['evilid', 'goodid']"""
	d = unpack("/cool/666", ['evilid', 'goodid'])
	for k,v in d.items(): print k, v

	print "\nkeep_blank_values=1"
	print """/cool/666/42 - ['evilid', 'goodid']"""
	d = unpack("/cool/666/42", ['evilid', 'goodid'], 1)
	for k,v in d.items(): print k, v
	
	print """/cool/666/42 - ['evilid']"""
	d = unpack("/cool/666/42", ['evilid'], 1)
	for k,v in d.items(): print k, v
 
	print """/cool/666 - ['evilid', 'goodid']"""
	d = unpack("/cool/666", ['evilid', 'goodid'], 1)
	for k,v in d.items(): print k, v
